package com.sunsharing.transport.file;

import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;
import com.sunsharing.common.Constant;
import com.sunsharing.common.Context;
import com.sunsharing.common.ContextCreate;
import com.sunsharing.common.URL;
import com.sunsharing.common.utils.StringUtils;
import com.sunsharing.transport.Channel;
import com.sunsharing.transport.IoHandle;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.sql.Time;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created with IntelliJ IDEA.
 * User: criss
 * Date: 13-4-30
 * Time: 下午12:49
 * To change this template use File | Settings | File Templates.
 */
public class FileChannel extends Channel {

    Logger logger = Logger.getLogger(FileChannel.class);

    public FileChannel(URL url,IoHandle io)
    {
        this.url = url;
        this.ioHandle = io;
        init();
    }

    public void init()
    {
        if(url.getIsClient().equals("false"))
        {
            //服务方需要监听目录
            String receivePath = url.getReceiveFilePath(url.getFromNodeId());
            Timer time = new Timer();
            time.schedule(new PathSearch(receivePath,this),0,10);
        }
    }

    @Override
    public void clone(Channel ch) {
    }

    @Override
    public void reconnect() {

    }

    protected void sendMsg(Context context)
    {
         String isclient = url.getIsClient();
         if(isclient.equals("true"))
         {
             //客户端发送文件到文件夹
             //String rootPath = url.getFileChannelPath();
             FileOutputStream out = null;
             try
             {
                 String path = url.getSendFilePath(url.getToNodeId());
                 out = new FileOutputStream(path+"/"+context.getMsgType()+
                         StringUtils.genUUID());
                 out.write(context.serialization());
                 out.write(Constant.FILE_END_TAG.getBytes());
             }catch (Exception e)
             {
                  logger.error("输出文件出错",e);
             }finally {
                 if(out!=null)
                 {
                     try
                     {
                        out.close();
                     }catch (Exception e)
                     {

                     }
                 }
             }
         }
    }

    @Override
    public boolean isclose() {
        return false;
    }
}

class PathSearch extends TimerTask
{
    Logger logger = Logger.getLogger(PathSearch.class);
    String path;
    Channel ch;
    public PathSearch(String path,Channel ch)
    {
        this.path = path;
        this.ch = ch;
    }
    byte []buffer = new byte[1024];
    public void run()
    {
        File p = new File(path);
        File[] fs = p.listFiles();
        if(fs.length>0)
        logger.error(path+"处理文件数:"+fs.length);
        for(int i=0;i<fs.length;i++)
        {
            if(fs[i].length()<13)
            {
                continue;
            }
            RandomAccessFile raf = null;
            try
            {
                raf = new RandomAccessFile(fs[i], "r");
                raf.seek(fs[i].length()-13);
                byte[] endTag = new byte[13];
                raf.read(endTag);
                if(new String(endTag).equals(Constant.FILE_END_TAG))
                {
                    //已经完整了可以读了
                    ByteOutputStream outputStream = new ByteOutputStream();
                    raf.seek(0);
                    int len = 0;
                    while((len = raf.read(buffer))!=-1)
                    {
                        outputStream.write(buffer,0,len);
                    }
                    byte[] o = outputStream.getBytes();
                    Context context = ContextCreate.createContextByByteArray(o,0,o.length-13);
                    ch.receive(context);
                    fs[i].delete();
                }
            }catch (Exception e)
            {
                logger.error("读取文件报错",e);
                //fs[i].renameTo();
            }finally {
                if(raf!=null)
                {
                    try
                    {
                        raf.close();
                    }catch (Exception e)
                    {

                    }
                }
            }
        }
    }
}
